package tk.heimashuma.store.web.controller;

import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import tk.heimashuma.store.entity.Users;
import tk.heimashuma.store.entity.vo.IphoneCode;
import tk.heimashuma.store.service.UserService;
import tk.heimashuma.store.utils.BoxUtils;
import tk.heimashuma.store.utils.RedisUtil;
import tk.heimashuma.store.utils.SmsSample;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @GetMapping(value = {"/login.html"})
    public String toLogin(){
        return "users/login";
    }
    @GetMapping(value = {"/register.html"})
    public String toRegister( Map<String,Object> map){
        return "users/register";
    }
    @PostMapping(value = {"/register"})
    public String register(Users  user, Map<String,Object> map){
        Optional<String> usernameOptional = Optional.ofNullable(user.getUsername());
        Optional<String> passwordOptional = Optional.ofNullable(user.getPassword());
        Optional<String> iphoneOptional = Optional.ofNullable(user.getIphone());
        if((usernameOptional.isPresent() && "".equals(usernameOptional.get())
                && passwordOptional.isPresent() && "".equals(passwordOptional.get())
                && iphoneOptional.isPresent() && "".equals(iphoneOptional.get()))){
            map.put("msg","必选参数为空");
            return "users/register";
        }
        // 发送激活邮件
        user.setEmailCode(UUID.randomUUID().toString().replace("-",""));
        userService.sendMailCode(user.getEmailCode(),user);
        userService.registerUser(user);
        return "redirect:/users/login.html";
    }
    @PostMapping(value = {"/login"})
    public String login(Users user, Map<String,Object> map, RedirectAttributes model, HttpSession session){
        if (session.getAttribute("user") != null){
            return "redirect:/index";
        }
        Optional<String> usernameOptional = Optional.ofNullable(user.getUsername());
        Optional<String> passwordOptional = Optional.ofNullable(user.getPassword());
        if(usernameOptional.isPresent() && "".equals(usernameOptional.get())
                && passwordOptional.isPresent() && "".equals(passwordOptional.get())){
            model.addFlashAttribute("msg","用户名或密码为空");
            return "redirect:/users/login.html";
        }
        Optional<Users> userOpt = Optional.ofNullable(userService.login(user));
        if(!userOpt.isPresent()){
            model.addFlashAttribute("msg","用户名或密码不正确");
            return "redirect:/users/login.html";
        }
        session.setAttribute("user",userOpt.get());
        return "redirect:/index";
    }
    @PostMapping(value = {"/checkIphoneCode"})
    public @ResponseBody Map<String, String> checkIphoneCode(HttpSession session, String code){

        Map<String,String> msg = new HashMap<>();
        Object object = session.getAttribute("iphoneCode");
        if(Optional.ofNullable(object).isPresent()){
            IphoneCode iphoneCode = (IphoneCode) object;
            long second= Duration.between(iphoneCode.getTime(), Instant.now()).getSeconds();
            if(300 > second){
                // 判断验证码是否超时
                if(iphoneCode.getCode().equals(code)){
                    // 判断验证码是否正确
                    msg.put("state","ok");
                }else{
                    msg.put("state","no");
                }
            }else{
                msg.put("state","timeout");
            }
        }else{
            msg.put("state","error");
        }
        return msg;
    }
    @PostMapping("/sendIphoneCode")
    public @ResponseBody Map<String, String> sendIphoneCode(HttpServletRequest request, HttpSession session, String iphone){
        Object o = redisUtil.hget("iphoneCode", request.getRemoteAddr());
        Map<String,String> msg = new HashMap<>();
        String state ;
        if(!Optional.ofNullable(o).isPresent()){
            redisUtil.hset("iphoneCode",request.getRemoteAddr(),iphone,60L);
            String code = BoxUtils.getRandomInt(6);
            IphoneCode iphoneCode = new IphoneCode();
            iphoneCode.setCode(code);
            iphoneCode.setTime(Instant.now());
            //TODO 手机验证码临时
            state = SmsSample.sendIphoneCode(iphone, code);
            System.out.println(code);
            session.setAttribute("iphoneCode",iphoneCode);
        }else {
            state = "52";
        }


        if("0".equals(state)){
            msg.put("state","ok");
        }else if("51".equals(state)){
            msg.put("state","iphone number error");
        }else if("52".equals(state)){
            msg.put("state","no");
        }else{
            msg.put("state","短信接口出现问题");
        }
        return msg;
    }

    @PostMapping("/verify")
    public @ResponseBody Map<String, String> registerVerify(String type, String value){
        Map<String,String> msg = new HashMap<>();
        Boolean state = null;
        if("username".equals(type)) {
            state = userService.checkUsername(value);
        }else if("email".equals(type)){
            state = userService.checkEmail(value);
        }else if("iphone".equals(type)){
            state = userService.checkIphone(value);
        }
        if(null == state){
            msg.put("state","type error");
        }else{
            if(!state){
                msg.put("state","yes");
            }else{
                msg.put("state","no");
            }
        }
        return msg;
    }
    @GetMapping("/checkMail/{code}")
    public String checkMailCode(@PathVariable String code, Model model){
        boolean state = userService.checkMailCode(code);
        if(state)
            model.addAttribute("state","邮箱激活成功");
        else
            model.addAttribute("state","邮箱激活失败,亲不要重复激活");
        return "/users/mailVerify";
    }
    @PostMapping("/log_out")
    public @ResponseBody Map<String, Object> logOut(HttpSession session){
        Map<String,Object> msg= new HashMap<>();
        if(Optional.ofNullable(session.getAttribute("user")).isPresent()){
            session.removeAttribute("user");
            msg.put("state","ok");
        }else{
            msg.put("state","no");
        }
        return msg;
    }

}
